<?php
namespace app\screenshot\home;
use app\common\controller\Common;
use app\screenshot\model\ScreenshotOrder as TypeModel;
use app\screenshot\home\Wxpay;
use think\Db;
use think\Loader;
Loader::import('WxPay.WxPayPubHelper',EXTEND_PATH,'.php');


class Buy extends Common
{
    public function index()
    {
        //生成一个订单
        $mod = new TypeModel();
        if (!$mod->storage()) {
            return $this->error($mod->getError());
        }
        //返回订单ids
        return json(["data" => $mod->getLastInsID()]);
    }
    public function wxpay(){
   
        $jsApi = new \JsApi_pub();

        $money =  (float)input("money", '', 'htmlspecialchars_decode') * 100;
        //$money = 1;
        $order_id = input("orderid");
    
        //=========步骤1：网页授权获取用户openid============
        //通过code获得openid
        
        $openid = input("openid", '', 'htmlspecialchars_decode');
    
        
        //=========步骤2：使用统一支付接口，获取prepay_id============
        //使用统一支付接口
        $unifiedOrder = new \UnifiedOrder_pub();
        
        //设置统一支付接口参数
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //spbill_create_ip已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $unifiedOrder->setParameter("openid",$openid);//商品描述
     
        $unifiedOrder->setParameter("body","购买vip");//商品描述
        $unifiedOrder->setParameter("sign_type","MD5");//商品描述
            $unifiedOrder->setParameter("device_info","WEB");//商品描述
        //自定义订单号，此处仅作举例
        $timeStamp = time();
    
        $out_trade_no = 'SCREENSHOT'.$order_id;

        $unifiedOrder->setParameter("out_trade_no", "$out_trade_no");//商户订单号 
        $unifiedOrder->setParameter("total_fee",$money);//总金额
        $unifiedOrder->setParameter("notify_url",\WxPayConf_pub::NOTIFY_URL);//通知地址 
        $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
        //非必填参数，商户可根据实际情况选填
        //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号  
        //$unifiedOrder->setParameter("device_info","XXXX");//设备号 
        //$unifiedOrder->setParameter("attach","XXXX");//附加数据 
        //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
        //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间 
        //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记 
        //$unifiedOrder->setParameter("openid","XXXX");//用户标识
        //$unifiedOrder->setParameter("product_id","XXXX");//商品ID
        
        $arr = array();
        $arr['prepay_id'] = $unifiedOrder->getPrepayId();
        $arr['nonce_str']=$unifiedOrder->parameters["nonce_str"]; 
        $arr['timeStamp'] = (String)$timeStamp;
   
        $stringA="appId=".\WxPayConf_pub::APPID."&nonceStr=$arr[nonce_str]&package=".'prepay_id='."$arr[prepay_id]&signType=MD5&timeStamp=$timeStamp";
        $stringSignTemp="$stringA&key=".\WxPayConf_pub::KEY;  
        
        $sign=MD5($stringSignTemp);  
        $arr['sign']=strtoupper($sign); 
        return json($arr);

    }
    public function paySuccess()
    {
        $order_id = input("order_id", '', 'htmlspecialchars_decode');
        $row = TypeModel::where("id",$order_id)->find();
        if($row['status'] == 1) {
            return 1;
        }
    
    }
    public function notify(){

        $notify = new \Notify_pub();

	    //存储微信的回调
	    $xml = file_get_contents("php://input");	
	    $notify->saveData($xml);
		
	  //  $returnXml = $notify->returnXml();
	    $log_name="C://notify_url.log";//log文件路径
	
        $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        
	    $order_id = substr($notify->data["out_trade_no"],10);
	    $total_fee = $notify->data["total_fee"];
	    $pay_user = $notify->data["openid"];
        $row = TypeModel::where("id",$order_id)->find();
	    if($notify->data["return_code"] == "SUCCESS"){
            
            if($total_fee == ($row['price'] * 100)) {
                //处理设置订单支付成功
                db::name('screenshot_order')->where('id',$order_id)->update(['status'=>'1']);
                db::name('admin_member')->where('id',$row['uid'])->update(['vip_start_time'=>time()]);
                if($row['vipTime'] == 'ever') {
                    $end_time = 'ever';
                }else{
                    $end_time = strtotime("+".$row['vipTime']." day");
                }
                
                db::name('admin_member')->where('id',$row['uid'])->update(['vip_end_time'=>$end_time]);

            }
            
		    $this->log_result($log_name,"【succsss】:\n".$xml."\n");
            $this->return_xml_success('OK');
            return true;
        }
    }

    function  log_result($file,$word) 
	{
	    $fp = fopen($file,"a");
	    flock($fp, LOCK_EX) ;
	    fwrite($fp,"执行日期：".strftime("%Y-%m-%d-%H：%M：%S",time())."\n".$word."\n\n");
	    flock($fp, LOCK_UN);
	    fclose($fp);
    }

    private function set_xml($args)
    {
        $xml = "<xml>";
        foreach ($args as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml; 
    }
    private function return_xml_success($msg){
        $arr = array(
            'return_code'   =>  'SUCCESS',
            'return_msg'    =>  $msg
        );
        echo $this->set_xml($arr);
        exit();
    }
}